/*
 * File:    Xpath.java
 * Created: 19-Feb-2009
 * Version: $Id$
 *
 * COPYRIGHT (C) 2009, Bitgate Mobile, LLC.  All Rights Reserved.
 *
 * software@bitgatemobile.com
 */

package com.webplasm.render.tags.u;

import java.util.Arrays;
import java.util.List;

import org.w3c.dom.Node;

import com.bitgate.util.node.XPathParser;
import com.webplasm.context.RenderContext;
import com.webplasm.render.engine.RenderException;
import com.webplasm.render.tags.TagInterface;
import com.webplasm.render.tags.WrappedNode;
import com.webplasm.store.VariableStoreInterface;
import com.webplasm.store.VariableContainer.VariableType;

/**
 * Provides a mechanism to traverse an XML document stored in a variable using XPath expressions.
 * 
 * @author kenji
 * @since Webplasm 1.0
 */
public class Xpath extends WrappedNode implements TagInterface {
	private static final String DESCRIPTION = "Performs an XPath expression against the contents of an XML parsed node object.";

	public String getNamespace() {
		return "u";
	}
	
	public List<String> getAttributes() {
		return Arrays.asList("var");
	}
	
	public List<String> getManagedNodes() {
		return null;
	}

	public String getDescription() {
		return DESCRIPTION;
	}

	@Override
	public StringBuffer render(RenderContext rContext) throws RenderException {
		if (elements.get("var") == null) {
			throw new RenderException("u:xpath requires variable name");
		}
		
		VariableStoreInterface vsInterface = rContext.getVariableStore().getVariable(elements.get("var"), VariableType.NODE);
		Object nodeObject = vsInterface.getObject();
		
		if (nodeObject == null) {
			throw new RenderException("u:xpath requires a variable name that has a node object associated with it.");
		}
		
		Node nodeValue = (Node) nodeObject;
		String xpathExpression = super.render(rContext).toString();
		
		return new StringBuffer(XPathParser.parse(nodeValue, xpathExpression));
	}
}